import { G } from "./utils/Gloabl";

const { ccclass, property } = cc._decorator;

@ccclass
export class Controller extends cc.Component {

    @property(cc.Node)
    btnA: cc.Node = null;
    @property(cc.Node)
    btnS: cc.Node = null;
    @property(cc.Node)
    btnW: cc.Node = null;
    @property(cc.Node)
    btnD: cc.Node = null;

    

    onLoad() {
        cc.systemEvent.on("keydown", this.onKeyDown, this);
        cc.systemEvent.on("keyup", this.onKeyUp, this);

        this.btnA.on("touchstart", this.onTouchStart, this);
        this.btnS.on("touchstart", this.onTouchStart, this);
        this.btnW.on("touchstart", this.onTouchStart, this);
        this.btnD.on("touchstart", this.onTouchStart, this);

        this.btnA.on("touchend", this.onTouchEnd, this);
        this.btnS.on("touchend", this.onTouchEnd, this);
        this.btnW.on("touchend", this.onTouchEnd, this);
        this.btnD.on("touchend", this.onTouchEnd, this);
    }

    onTouchStart(e: cc.Event.EventTouch) {
        let keyCode: cc.macro.KEY;
        switch (e.currentTarget) {
            case this.btnA:
                keyCode = cc.macro.KEY.a;
                break;
            case this.btnS:
                keyCode = cc.macro.KEY.s;
                break;
            case this.btnW:
                keyCode = cc.macro.KEY.w;
                break;
            case this.btnD:
                keyCode = cc.macro.KEY.d;
                break;
        }
        G.Input[keyCode] = 1;
    }

    onTouchEnd(e: cc.Event.EventTouch) {
        let keyCode: cc.macro.KEY;
        switch (e.currentTarget) {
            case this.btnA:
                keyCode = cc.macro.KEY.a;
                break;
            case this.btnS:
                keyCode = cc.macro.KEY.s;
                break;
            case this.btnW:
                keyCode = cc.macro.KEY.w;
                break;
            case this.btnD:
                keyCode = cc.macro.KEY.d;
                break;
        }
        G.Input[keyCode] = 0;
    }

    onKeyDown(e: cc.Event.EventKeyboard): void {
        G.Input[e.keyCode] = 1;
    }

    onKeyUp(e: cc.Event.EventKeyboard): void {
        G.Input[e.keyCode] = 0;
    }

    onDestroy() {
        cc.systemEvent.off("keydown", this.onKeyDown, this);
        cc.systemEvent.off("keyup", this.onKeyUp, this);

        this.btnA.off("touchstart", this.onTouchStart, this);
        this.btnS.off("touchstart", this.onTouchStart, this);
        this.btnW.off("touchstart", this.onTouchStart, this);
        this.btnD.off("touchstart", this.onTouchStart, this);

        this.btnA.off("touchend", this.onTouchEnd, this);
        this.btnS.off("touchend", this.onTouchEnd, this);
        this.btnW.off("touchend", this.onTouchEnd, this);
        this.btnD.off("touchend", this.onTouchEnd, this);
    }
}